import Mock from 'mockjs'

// 模拟api接口
// Mock.mock('/api/user/list',{ list:[ {},{} ] })
// Mock.mock('/api/user/list',()=>{ return [] })
// Mock.mock('/api/user/list','get',()=>{ return [] })
// Mock.mock('/api/user/list','post',()=>{ return [] })

var data = {};

//生成数据
if( localStorage.getItem('user_list') ){
    data = JSON.parse( localStorage.getItem('user_list') )
}else{
    //生成数据
    data = Mock.mock({
        "list|100":[
            {
                id:'@id',
                name:'@cname',
                'age|20-30':1,
                'sex|1':false,
                'phone|13000000000-19999999999':1,
                date:'@Date',
                email:'@email',
                address:'@county(true)'
            }
        ]
    })
    //保存数据到本地存储
    localStorage.setItem('user_list',JSON.stringify( data ))
}

//查询接口
Mock.mock('/api/user/list','get',()=>{  
    //返回数据
    return data;
})

//删除接口
Mock.mock('/api/user/delete','post',(req)=>{  
    //接收参数 , req.body 是字符串格式,需要转为json对象
    // console.log( req.body );
    var { id } = JSON.parse( req.body );
    
    //通过id, 找到要删除的那一条数据, 执行删除
    var i = data.list.findIndex((item)=>{
        return item.id == id;
    })
    if( i != -1 ){
        data.list.splice(i,1);
        localStorage.setItem('user_list',JSON.stringify( data ));
    }

    return {status:200,msg:'删除成功!',list:data.list}
})

